package com.merchant.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import com.merchant.constant.Constants;
import com.merchant.json.ReadJson;
import com.merchant.manage.ManageFoodsOrederDetail;
import com.merchant.util.LoadingDialog;
import com.zjxfood.merchant.activity.R;

public class FragmentAllOrders extends Fragment {
	protected View mContentView;// 当前内容View
	private ListView mListView;
	private List<Map<String, Object>> mlistitem;
	private HashMap<String, Object> mUserMapLists;
	private ArrayList<HashMap<String, Object>> mDataList;
	private ArrayList<HashMap<String, Object>> addDataList;
	private MyAdapter adapter;
	private String page = "1";
	private int lastVisibleIndex;
	private int x = 1;
	private RunTask mRunTask;
	private LoadingDialog dialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContentView = inflater.inflate(R.layout.fragment_all_order, container,
				false);
		// new Thread(GetMOrderList).start();
		dialog = new LoadingDialog(getActivity());
		dialog.show();
		init();
		mRunTask = new RunTask();
		mRunTask.execute("");
		return mContentView;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	private void init() {
		mListView = (ListView) mContentView.findViewById(R.id.listView);
		mlistitem = getData();
		mListView.setOnScrollListener(mScrollListener);
		// MyAdapter adapter = new MyAdapter(getActivity(), mDataList);
		// mListView.setAdapter(adapter);
		// mListView.setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		// long arg3) {
		// // TODO Auto-generated method stub
		// Intent intent = new Intent();
		// intent.setClass(getActivity(), ManageFoodsOrederDetail.class);
		// startActivity(intent);
		// }
		// });
	}

	private List<Map<String, Object>> getData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		for (int i = 0; i < 10; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			// String url = "http://10.167.12.184:8080/examples/image/1.png";
			//
			// Bitmap bitmap = getImageByURL(url);

			// map.put("user_reviews_imageview", R.drawable.photo3);
			map.put("user_reviews_text1", "25555555");
			map.put("user_reviews_text2", "250");
			map.put("user_reviews_text3", "250");
			list.add(map);
		}
		return list;

	}

	Runnable GetMOrderList = new Runnable() {

		@Override
		public void run() {
			try {
				String ss = "mid=" + 32 + "&orderStatusCode=" + 0
						+ "&pageSize=" + 10 + "&currentPage=" + 1;
				String sign = Constants.sortsStr(ss);
				String str = Constants.GetMOrderList + sign + "&mid=" + 32
						+ "&orderStatusCode=" + 0 + "&pageSize=" + 10
						+ "&currentPage=" + 1;
				String json = ReadJson.readParse(str);
				mUserMapLists = Constants.getJson2Object(json);
				mDataList = Constants.getJsonArray(mUserMapLists.get("Data")
						.toString());
				Log.i("mUserMap", "================" + mUserMapLists);
				// handler.sendEmptyMessageDelayed(1, 0);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	class RunTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... strs) {
			switch (x) {
			case 1:
				try {
					String ss = "mid=" + 32 + "&orderStatusCode=" + 0
							+ "&pageSize=" + 10 + "&currentPage=" + page;
					String sign = Constants.sortsStr(ss);
					String str = Constants.GetMOrderList + sign + "&mid=" + 32
							+ "&orderStatusCode=" + 0 + "&pageSize=" + 10
							+ "&currentPage=" + page;
					String json = ReadJson.readParse(str);
					// Log.i("sign", "================" + json);
					mUserMapLists = Constants.getJson2Object(json);
					mDataList = Constants.getJsonArray(mUserMapLists
							.get("Data").toString());
					// mMap = Constants.getJsonArray(json);
					handler.sendEmptyMessageDelayed(1, 0);
					Log.i("mDataList", "================" + mDataList);
					dialog.dismiss();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					dialog.dismiss();
					handler.sendEmptyMessageDelayed(3, 0);
					e.printStackTrace();
				}
				break;

			case 2:
				String ss = "mid=" + 32 + "&orderStatusCode=" + 0
						+ "&pageSize=" + 10 + "&currentPage=" + page;
				String sign = Constants.sortsStr(ss);
				String str = Constants.GetMOrderList + sign + "&mid=" + 32
						+ "&orderStatusCode=" + 0 + "&pageSize=" + 10
						+ "&currentPage=" + page;
				String json;

				try {
					json = ReadJson.readParse(str);
					mUserMapLists = Constants.getJson2Object(json);
					addDataList = Constants.getJsonArray(mUserMapLists.get(
							"Data").toString());
					dialog.dismiss();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					dialog.dismiss();
					handler.sendEmptyMessageDelayed(3, 0);
					e.printStackTrace();
				}
				handler.sendEmptyMessageDelayed(2, 0);
				break;
			}

			return null;
		}
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				adapter = new MyAdapter(getActivity(), mDataList);
				mListView.setAdapter(adapter);
				// lv.addFooterView(mFooterView);
				// progressBar_member.setVisibility(View.GONE);
				mListView.setVisibility(View.VISIBLE);
				mListView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getActivity(),
								ManageFoodsOrederDetail.class);
						Bundle bundle = new Bundle();
						bundle.putString("orderid",
								mDataList.get(arg2).get("orderid").toString());
						intent.putExtras(bundle);
						startActivity(intent);
					}
				});
				break;
			case 2:
				adapter.nofity(addDataList);
				// mFooterProgressBar.setVisibility(View.GONE);
				// mFooterText.setVisibility(View.VISIBLE);
				// mFooterText.setText("数据加载已全部加载！");
				break;
			case 3:
				Toast.makeText(getActivity(), "请检查您的网络链接!", Toast.LENGTH_SHORT)
						.show();
				break;
			}
		};
	};
	OnScrollListener mScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
					&& lastVisibleIndex == adapter.getCount() - 1) {
				x = 2;
				// lv.addFooterView(mFooterView);// 添加 加载更多
				page = Integer.parseInt(page) + 1 + "";
				mRunTask = new RunTask();
				mRunTask.execute("");
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 计算最后可见条目的索引
			lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
		}
	};

	public final class ViewHolder {
		// public ImageView user_reviews_imageview;
		public TextView user_reviews_text1;
		public TextView user_reviews_text2;
		public TextView user_reviews_text3;
		public TextView foods_dc_check;

	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater flater;
		private ArrayList<HashMap<String, Object>> mList;

		public MyAdapter(Context content,
				ArrayList<HashMap<String, Object>> list) {
			this.flater = LayoutInflater.from(content);
			this.mList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void nofity(ArrayList<HashMap<String, Object>> list) {
			try {
				this.mList.addAll(list);
				notifyDataSetChanged();
			} catch (Exception e) {
				// TODO: handle exception
				handler.sendEmptyMessageDelayed(3, 0);
			}
		
		}

		@Override
		public View getView(final int position, View converView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder hodler = null;
			if (converView == null) {
				hodler = new ViewHolder();
				converView = flater.inflate(
						R.layout.manage_foods_yddc_list_item, null);

				hodler.user_reviews_text1 = (TextView) converView
						.findViewById(R.id.dc);
				hodler.user_reviews_text2 = (TextView) converView
						.findViewById(R.id.dc1);
				hodler.user_reviews_text3 = (TextView) converView
						.findViewById(R.id.dc2);
				hodler.foods_dc_check = (TextView) converView
						.findViewById(R.id.foods_dc_check);
				converView.setTag(hodler);
			} else {
				hodler = (ViewHolder) converView.getTag();
			}
			// hodler.user_reviews_imageview
			// .setBackgroundResource((Integer) mlistitem.get(position)
			// .get("user_reviews_imageview"));
			hodler.user_reviews_text1.setText(mList.get(position)
					.get("orderid").toString());
			hodler.user_reviews_text2.setText(mList.get(position)
					.get("allcost").toString());
			hodler.user_reviews_text3.setText(mList.get(position)
					.get("deposit").toString());
//			hodler.foods_dc_check.setOnClickListener(new OnClickListener() {
//
//				@Override
//				public void onClick(View arg0) {
//					// TODO Auto-generated method stub
//					Intent intent = new Intent();
//					intent.setClass(getActivity(),
//							ManageFoodsOrederDetail.class);
//					Bundle bundle = new Bundle();
//					bundle.putString("orderid",
//							mDataList.get(position).get("orderid").toString());
//					intent.putExtras(bundle);
//					startActivity(intent);
//				}
//			});
			return converView;
		}

	}
}
